﻿global using Microsoft.AspNetCore.Http;
global using Microsoft.AspNetCore.Mvc;
global using Simple.Common;
global using Simple.Common.Helpers;
global using Simple.Services;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OpenApi.Models;
using NLog;
using NLog.Web;
using Simple.Common.Authorization;
using Simple.Common.Models;
using Simple.Repository.Extensions;
using Simple.Services.Components;
using Simple.Services.Permissions;
using Simple.Services.System.Jobs;

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("启动中……");

try
{
    var builder = WebApplication.CreateBuilder(args);


    // 基本能力配置
    builder.SimpleConfigure();

    var configuration = builder.Configuration;

    builder.WebHost.UseUrls("http://*:5216");

    // API
    builder.Services
            //全局路由前缀配置
            .AddControllers(option =>
            {
                if (configuration["Environment"].Equals("Production"))
                {
                    //就是在所有路由前面增加的名称
                    option.Conventions.Insert(0, new RouteConventio(new RouteAttribute("api/swpu/hd/")));
                }
                else
                {
                    //就是在所有路由前面增加的名称
                    option.Conventions.Insert(0, new RouteConventio(new RouteAttribute("api/")));
                }
            })
            .AddDataValidation()
            .AddAppResult(options =>
            {
                options.ResultFactory = resultException =>
                {
                    // AppResultException 都返回 200 状态码
                    var objectResult = new ObjectResult(resultException.AppResult);
                    objectResult.StatusCode = StatusCodes.Status200OK;
                    return objectResult;
                };
            });
    builder.Services.AddEndpointsApiExplorer();
    if (builder.Environment.IsDevelopment())
    {
        builder.Services.AddSimpleSwagger(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo { Title = "简单三层接口文档v1", Version = "v1" });
        });
    }
    // 获取连接字符串
    var connectionString = $"Data Source = ({ConfigHelper.ConfigDecrypt(configuration["DatabaseConfig:DataSource"])});User Id={ConfigHelper.ConfigDecrypt(configuration["DatabaseConfig:UserId"])};Password={ConfigHelper.ConfigDecrypt(configuration["DatabaseConfig:Password"])};Pooling=True;Max Pool Size=800;Min Pool Size=80;Connection Timeout=50;Incr Pool Size=10;";
    builder.Services.AddSingleton<IDbConfig>(new DbConfig(connectionString));
    // 仓储层
    //两只
    //builder.Services.AddRepository(configuration["ConnectionStrings:MyOracleDatabase"]);
    builder.Services.AddRepository(connectionString);
    // 服务层：添加基础服务
    builder.Services.AddSimpleBaseServices();
    // 服务层：自动添加 Service 层以 Service 结尾的服务
    builder.Services.AddAutoServices("Simple.Services");

    //// Cookie 认证
    builder.Services.AddCookieAuthentication();
    // JWT 认证
    builder.Services.AddJwtAuthentication();
    // 授权
    builder.Services.AddSimpleAuthorization();
    // 替换默认 PermissionChecker
    builder.Services.Replace(new ServiceDescriptor(typeof(IPermissionChecker), typeof(PermissionChecker), ServiceLifetime.Transient));

    // 对象映射 AutoMapper
    var profileAssemblies = AssemblyHelper.GetAssemblies(); // 这里读取整个项目程序集，也可以选择只读指定程序集，如: "Simple.Services"
    builder.Services.AddAutoMapper(profileAssemblies, ServiceLifetime.Singleton);

    // 缓存
    builder.Services.AddSimpleCache();

    // JsonOptions
    builder.Services.AddSimpleJsonOptions();

    // 跨域
    builder.Services.AddSimpleCors();


    //// 定时任务
    //builder.Services.AddJobScheduling(options =>
    //{
    //    options.StartHandle = async sp =>
    //    {
    //        var jobService = sp.GetService<IJobService>();
    //        if (jobService == null) return;
    //        await jobService.StartAll();
    //    };
    //});

    // 演示环境替换服务 Begin -----------
    // 如果要正常使用系统功能（如：定时任务的功能），请将这部分注释
    // 演示环境替换服务 End -----------

    var app = builder.Build();

    // 配置 HTTP 请求管道 --------------------------

    // 添加自定义中间件（包含：Body重复读取、异常处理）
    app.UseSimplePipeline();

    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI(options =>
        {
            options.SwaggerEndpoint("/swagger/v1/swagger.json", "Simple API v1");
        });
    }


    // UseCors 必须在 UseRouting 之后，UseResponseCaching、UseAuthorization 之前
    app.UseCors();
    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseDeveloperExceptionPage();
    app.MapControllers();

    app.Run();
}
catch (Exception ex)
{
    logger.Error(ex, "由于发生异常，导致程序中止！");
    throw;
}
finally
{
    LogManager.Shutdown();
}
